package com.example.bluetooth.commonUtil;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.widget.Toast;

import com.example.bluetooth.ble.listener.OnScanDeviceListener;
import com.example.bluetooth.ble.scanle.ScanLeImpl;
import com.example.bluetooth.ble.service.BluetoothLeService;


/**
 * Created by neil on 2018/3/6.
 */

public abstract class BleBluetoothUtil implements IBluetoothUtil {
    private Activity mActivity;
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    public boolean init(Activity activity) {
        mActivity = activity;
        if (!activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("不支持BLE");
            return false;
        }
        //获取蓝牙适配器
        if (mBluetoothAdapter == null)
            mBluetoothAdapter = ((BluetoothManager) mActivity.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
        //检查手机是否支持蓝牙
        if (mBluetoothAdapter == null) {
            showToast("不支持BLE");
            return false;
        }
        if (!BluetoothLeService.getInstance().initialize()) {
            showToast("不支持蓝牙设备");
            return false;
        }
        ScanLeImpl.getInstance().setOnScanDeviceListener(new OnScanDeviceListener() {
            @Override
            public void onScanDevice(BluetoothDevice device, int rssi) {
                onFoundDevices(device, rssi, null);
            }
        });
        return true;
    }

    @Override
    public boolean isEnabled() {
        if (mBluetoothAdapter == null) {
            return false;
        }
        return mBluetoothAdapter.isEnabled();
    }

    @Override
    public boolean startScan() {
        showToast("正在寻找蓝牙设备");
        ScanLeImpl.getInstance().scanLeDevice(true, 30);
        return true;
    }

    @Override
    public boolean stopScan() {
        ScanLeImpl.getInstance().stopLeScan();
        return false;
    }

    @Override
    public abstract void onFoundDevices(BluetoothDevice devices, int rssi, byte[] scanRecord);

    private void showToast(final String msg) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
